import { Code, CODE_SUCC, MSG_CODE_ERR_UNKOWN } from "./code";

/**
 * 处理结果规范,如果方法返回此类型对象,则表示方法一定不会出现异常
 */
export class Result<R = undefined> {
	/**
	 * 是否处理成功
	 */
	private success: boolean;
	/**
	 * 处理消息
	 */
	private code: Code;
	/**
	 * 携带的返回结果
	 */
	private result?: R;

	constructor(success: boolean, code: Code, result?: R) {
		this.success = success;
		this.code = code;
		this.result = result;
	}

	isSuccess(): boolean {
		return this.success;
	}

	getCode(): Code {
		return this.code;
	}

	getResult(): R | undefined {
		return this.result;
	}

	static succ<S>(res?: S): Result<S> {
		return new Result(true, CODE_SUCC, res);
	}

	private static likeError(like: any): Error | undefined {
		if (like.message && like.stack) {
			if (!like.name) {
				like.name = "unkown error";
			}
			return like as Error;
		}
	}

	static fail(msgOrCode?: String | string | Code | Error): Result<never> {
		if (!msgOrCode) {
			const code = new Code(MSG_CODE_ERR_UNKOWN, "未知的错误");
			return new Result(false, code);
		}
		if (msgOrCode instanceof String || typeof msgOrCode == "string") {
			const code = new Code(MSG_CODE_ERR_UNKOWN, msgOrCode as string);
			return new Result(false, code);
		}
		if (msgOrCode instanceof Error) {
			const code = new Code(
				MSG_CODE_ERR_UNKOWN,
				msgOrCode.message,
				undefined,
				msgOrCode
			);
			return new Result(false, code);
		}
		const likeErr = Result.likeError(msgOrCode);
		if (likeErr) {
			const code = new Code(
				MSG_CODE_ERR_UNKOWN,
				likeErr.message,
				undefined,
				likeErr
			);
			return new Result(false, code);
		}
		return new Result(false, msgOrCode as Code);
	}
}
